package com.ruoyi.yscggl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.yscggl.domain.Jfsbmx;
import com.ruoyi.yscggl.domain.Shb;
import com.ruoyi.yscggl.domain.bo.JfsbmxBo;
import com.ruoyi.yscggl.domain.vo.JfsbmxVo;
import com.ruoyi.yscggl.domain.vo.ShbVo;
import com.ruoyi.yscggl.mapper.JfsbmxMapper;
import com.ruoyi.yscggl.mapper.ShbMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.yscggl.domain.bo.JfsbBo;
import com.ruoyi.yscggl.domain.vo.JfsbVo;
import com.ruoyi.yscggl.domain.Jfsb;
import com.ruoyi.yscggl.mapper.JfsbMapper;
import com.ruoyi.yscggl.service.IJfsbService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

/**
 * 经费申报Service业务层处理
 *
 * @author jiayuan
 * @date 2023-04-20
 */
@RequiredArgsConstructor
@Service
public class JfsbServiceImpl implements IJfsbService {

    private final IdentifierGenerator identifierGenerator;

    private final JfsbMapper baseMapper;

    private final JfsbmxMapper jfsbmxMapper;

    private final ShbMapper shbMapper;

    /**
     * 查询经费申报
     */
    @Override
    public JfsbVo queryById(Long id){
        JfsbVo jfsbVo = baseMapper.selectVoById(id);
        if (ObjectUtil.isNotNull(jfsbVo)) {
            List<JfsbmxVo> items = jfsbmxMapper.selectVoList(Wrappers.<Jfsbmx>lambdaQuery().eq(Jfsbmx::getPnNo, jfsbVo.getFsubNo()));
            jfsbVo.setItems(items);
            List<ShbVo> audits = shbMapper.selectVoList(Wrappers.<Shb>lambdaQuery().eq(Shb::getPnNo, jfsbVo.getFsubNo()));
            jfsbVo.setAudits(audits);
        }
        return jfsbVo;
    }

    /**
     * 查询经费申报列表
     */
    @Override
    public TableDataInfo<JfsbVo> queryPageList(JfsbBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Jfsb> lqw = buildQueryWrapper(bo);
        Page<JfsbVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询经费申报列表
     */
    @Override
    public List<JfsbVo> queryList(JfsbBo bo) {
        LambdaQueryWrapper<Jfsb> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Jfsb> buildQueryWrapper(JfsbBo bo) {
        LambdaQueryWrapper<Jfsb> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getFsubNo()), Jfsb::getFsubNo, bo.getFsubNo());
        lqw.like(StringUtils.isNotBlank(bo.getFsubName()), Jfsb::getFsubName, bo.getFsubName());
        lqw.eq(StringUtils.isNotBlank(bo.getFsubType()), Jfsb::getFsubType, bo.getFsubType());
        lqw.eq(StringUtils.isNotBlank(bo.getDeptNo()), Jfsb::getDeptNo, bo.getDeptNo());
        lqw.like(StringUtils.isNotBlank(bo.getDeptName()), Jfsb::getDeptName, bo.getDeptName());
        lqw.eq(StringUtils.isNotBlank(bo.getAppPerNo()), Jfsb::getAppPerNo, bo.getAppPerNo());
        lqw.eq(StringUtils.isNotBlank(bo.getAppPer()), Jfsb::getAppPer, bo.getAppPer());
        lqw.eq(StringUtils.isNotBlank(bo.getTel()), Jfsb::getTel, bo.getTel());
        lqw.eq(bo.getAppDate() != null, Jfsb::getAppDate, bo.getAppDate());
        if (bo.getAppDateArray() != null && bo.getAppDateArray().length == 2) {
            lqw.between(Jfsb::getAppDate, bo.getAppDateArray()[0], bo.getAppDateArray()[1]);
        }
        lqw.eq(StringUtils.isNotBlank(bo.getState()), Jfsb::getState, bo.getState());
        lqw.eq(StringUtils.isNotBlank(bo.getRtNo()), Jfsb::getRtNo, bo.getRtNo());
        lqw.like(StringUtils.isNotBlank(bo.getRtName()), Jfsb::getRtName, bo.getRtName());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyReason()), Jfsb::getApplyReason, bo.getApplyReason());
        lqw.eq(bo.getBudget() != null, Jfsb::getBudget, bo.getBudget());
        lqw.eq(StringUtils.isNotBlank(bo.getFzrNo()), Jfsb::getFzrNo, bo.getFzrNo());
        lqw.like(StringUtils.isNotBlank(bo.getFzrName()), Jfsb::getFzrName, bo.getFzrName());
        lqw.eq(StringUtils.isNotBlank(bo.getIsImport()), Jfsb::getIsImport, bo.getIsImport());
        lqw.like(StringUtils.isNotBlank(bo.getFsubFzrName()), Jfsb::getFsubFzrName, bo.getFsubFzrName());
        lqw.eq(StringUtils.isNotBlank(bo.getFsubFzrNo()), Jfsb::getFsubFzrNo, bo.getFsubFzrNo());
        lqw.like(StringUtils.isNotBlank(bo.getFsubTypeName()), Jfsb::getFsubTypeName, bo.getFsubTypeName());
        lqw.eq(StringUtils.isNotBlank(bo.getYusnd()), Jfsb::getYusnd, bo.getYusnd());
        return lqw;
    }

    private void setDefaultValue(JfsbBo bo) {
        // 生成雪花算法id
        String no = ((Long) identifierGenerator.nextId(null)).toString();
        // 申报编号赋值
        bo.setFsubNo(no);
        // 申请人赋值
        bo.setAppPerNo(LoginHelper.getUserId().toString());
        bo.setAppPer(LoginHelper.getNickName());
        // 申请日期
        bo.setAppDate(DateUtils.getNowDate());
        // 部门赋值
        bo.setDeptNo(LoginHelper.getLoginUser().getDeptId().toString());
        bo.setDeptName(LoginHelper.getLoginUser().getDeptName());
    }

    /**
     * 新增经费申报
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(JfsbBo bo) {
        // 为编号、申请人、申请时间、部门等信息赋值
        setDefaultValue(bo);
        Jfsb add = BeanUtil.toBean(bo, Jfsb.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            List<JfsbmxBo> items = CollectionUtil.isNotEmpty(bo.getItems()) ? bo.getItems() : new ArrayList<>();
            for (int i = 0; i < items.size(); i++) {
                Jfsbmx item = BeanUtil.toBean(items.get(i), Jfsbmx.class);
                // 申报编号赋值
                item.setPnNo(bo.getFsubNo());
                // 生成雪花算法id
                String itemNo = ((Long) identifierGenerator.nextId(null)).toString();
                // 明细编号赋值
                item.setAsNo(itemNo);
                // 计算总金额
                flag = jfsbmxMapper.insert(item) > 0;
                if (flag) {
                    items.get(i).setId(item.getId());
                }
            }
        }
        return flag;
    }

    /**
     * 修改经费申报
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(JfsbBo bo) {
        Jfsb update = BeanUtil.toBean(bo, Jfsb.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 判断是否有删除的明细
            if (StringUtils.isNotEmpty(bo.getDelItemIds())) {
                String[] delIds = bo.getDelItemIds().substring(0, bo.getDelItemIds().length() - 1).split(",");
                ArrayList<String> ids = CollectionUtil.toList(ArrayUtil.remove(delIds, delIds.length));
                jfsbmxMapper.deleteBatchIds(ids);
            }
            List<JfsbmxBo> items = bo.getItems();
            for (int i = 0; i < items.size(); i++) {
                Jfsbmx item = BeanUtil.toBean(items.get(i), Jfsbmx.class);
                // 判断明细id是否为空，该进行insert还是update
                if (ObjectUtil.isEmpty(item.getId())) {
                    // 生成雪花算法id
                    String itemNo = ((Long) identifierGenerator.nextId(null)).toString();
                    // 申报编号及明细编号赋值
                    item.setAsNo(itemNo);
                    item.setPnNo(bo.getFsubNo());
                    flag = jfsbmxMapper.insert(item) > 0;
                } else {
                    flag = jfsbmxMapper.updateById(item) > 0;
                }
                if (!flag) {
                    return flag;
                }
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Jfsb entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除经费申报
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<Jfsb> jfsbs = baseMapper.selectBatchIds(ids);
        int delCount = 0;
        for (int i = 0; i < jfsbs.size(); i++) {
            jfsbmxMapper.delete(Wrappers.<Jfsbmx>lambdaQuery().eq(Jfsbmx::getPnNo, jfsbs.get(i).getFsubNo()));
            delCount = baseMapper.deleteById(jfsbs.get(i)) + delCount;
        }
        return delCount > 0;
    }
}
